package bidsanity

/*
    B-1: Bids have the following required fields: amount and date/time of bid (unit test)
    B-2: Bids are required to be for a Listing (unit test)
    B-3: Bids are required to have a bidder (Customer) (unit test)
    B-4: A Listing has a list of Bids for that Listing (unit test)
    B-5: The Bid amount must be at least .50 higher than the previous Bid for the same listing (integration test)
    B-6: When a Listing is saved, any new Bids added for the listing must be saved (integration test)
 */
class Bid {
    Double amount
    Customer bidder
    Date bidTime = new Date()


    static belongsTo = [listing: Listing]
    static constraints = {
        amount(nullable:false, validator: {value, bid->
            if (bid.id != null) {return true } //this gets called for existing bids on the listing too, so bail out.
            def result = true
            if(bid.listing?.bids?.size() > 1)
            {
                def sortedBids = bid.listing.bids.sort {it.amount}.reverse()
                def previousHighBid
                if (sortedBids[0] == bid) { previousHighBid = sortedBids[1]}
                else { previousHighBid = sortedBids[0]}
                result = (bid.amount >= (previousHighBid.amount + 0.5))
            }
            else if (bid.amount < (bid.listing?.startingBidPrice)){
                result = false
            }
            return result
        })
        bidder(nullable:false)
        bidTime(nullable: false)
        listing(nullable: false)
    }

    static mapping ={
        bidder lazy: false
    }


    static namedQueries = {
        mostRecent { listingId ->
            eq 'listing.id', listingId
            order("bidTime", "desc")
            maxResults(10)
        }
    }
}
